package com.guli.common.utils;
/*
 * @Author 罗
 * @date 2020/9/11 - 8:48 下午
 */

import com.guli.common.pojo.vo.ParentAndChildren;
import com.guli.common.pojo.vo.TreeNode;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class ListToTree {

    /**
     * 注意同文件夹下有和范型变量名相同的类，需要在方法的void 之前声明好
     */
    public static <T extends ParentAndChildren<R>, R> void parse(List<T> list, TreeNode<T> treeNode, R parentId, Comparator<TreeNode<T>> comparator) {

        T tempNode = null;

        TreeNode<T> node = null;
        for (int i = 0; i < list.size(); i++) {
            tempNode = list.get(i);
            if (parentId.equals(tempNode.getParentId())) {

                createChildrenIfNotExist(treeNode);

                node = new TreeNode<>();

                node.setNode(tempNode);

                treeNode.getChildren().add(node);

                list.remove(i);

                i--;

                parse(list, node, node.getNode().getId(), comparator);
            }
        }

        if (!ObjectUtils.isEmpty(node) && !ObjectUtils.isEmpty(node.getChildren())) {
            QuickSort.sort(node.getChildren(), 0, node.getChildren().size()-1, comparator);
        }


    }

    private static <T> void createChildrenIfNotExist(TreeNode<T> treeNode) {
        if (ObjectUtils.isEmpty(treeNode.getChildren())) {
            treeNode.setChildren(new ArrayList<TreeNode<T>>());
        }
    }


}
